package com.sun.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ThenComposeExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 模拟获取用户ID
        CompletableFuture<String> userIdFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("获取用户ID线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "user-123";
        });

        // thenCompose: 将前一个任务的结果作为输入，返回一个新的CompletableFuture
        CompletableFuture<String> userDetailFuture = userIdFuture.thenCompose(userId -> {
            System.out.println("thenCompose执行线程: " + Thread.currentThread().getName());
            // 基于用户ID获取用户详情
            return CompletableFuture.supplyAsync(() -> {
                System.out.println("获取用户详情线程: " + Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
                return "用户详情 for " + userId;
            });
        });

        System.out.println("用户详情: " + userDetailFuture.get());
        System.out.println("主线程结束");
    }
}
